package ATM.data;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import ATM.gui.Screen;

/**
 * 
 * @author Muhamed
 * 
 */
public class AtmData {

	protected static final String DATABASE_URL = "jdbc:mysql://localhost/atm";
	private static final String USERNAME = "root";
	private static final String PASSWORD = "hejsadu33";
	private Screen screen;
	protected Connection connection = null;
	protected Statement statement = null;
	protected ResultSet resultSet = null;
	protected PreparedStatement preparedStatement = null;
	PreparedStatement updateAvBal = null;
	PreparedStatement updateToBal = null;

	public AtmData(Screen screen) {
		this.screen = screen;
		try {
			connection = DriverManager.getConnection(DATABASE_URL, USERNAME,
					PASSWORD);
			statement = connection.createStatement();
			updateAvBal = connection
					.prepareStatement("UPDATE Accounts SET AvailableBalance = ? WHERE AccountID = ? ;");
			updateToBal = connection
					.prepareStatement("UPDATE Accounts SET TotalBalance = ? WHERE AccountID = ? ;");
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	public boolean Authenticated(String tfldUsername, String tfldPassword) {
		Boolean auth = false;

		try {
			resultSet = statement.executeQuery("SELECT ID, Password FROM id");
			while (resultSet.next()) {
				String username = resultSet.getString("ID");
				String password = resultSet.getString("Password");
				if (tfldUsername.equals(username)
						&& tfldPassword.equals(password)) {
					auth = true;
					break;
				}
			}
		} catch (SQLException sqlException) {
			sqlException.printStackTrace();
			close();
			closeR();
		}
		return auth;
	}

	public String Identification(String tfldUserName) {
		String ifc = null;

		try {
			resultSet = statement
					.executeQuery("SELECT Identification FROM id WHERE ID = "
							+ tfldUserName);
			resultSet.next();
			ifc = resultSet.getString("Identification");
		} catch (SQLException sqlException) {
			sqlException.printStackTrace();
			close();
			closeR();
		}
		return ifc;
	}

	public void close() {
		try {

			statement.close();
			connection.close();

		} catch (Exception e) {
			e.printStackTrace();

		}
	}

	public void closeR() {
		try {

			resultSet.close();

		} catch (Exception e) {
			e.printStackTrace();

		}
	}

}
